package services

import (
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"golang.org/x/crypto/ripemd160"
	"quickstart/global"
	"quickstart/models"
	"time"
)

type TokenService struct {
}

/**
获取token
*/
func (ts *TokenService) GetToken(token string) *models.UserToken {
	var userToken models.UserToken
	data := userToken.GetByToken(ts.getEncryptedToken(token))
	if data == nil {
		return nil
	}
	if data.Expiretime == 0 || data.Expiretime > time.Now().Unix() {
		data.Token = token
	} else {
		//ts.Delete(token)
	}
	return data
}

func (ts *TokenService) getExpiredIn(expiretime int64) int64 {
	return expiretime - time.Now().Unix()
}

/**
设置token
*/
func (ts *TokenService) Set(token string, userId int64) bool {
	token = ts.getEncryptedToken(token)
	o := orm.NewOrm()
	var userToken models.UserToken
	userToken.UserId = userId
	userToken.Token = token
	userToken.Createtime = time.Now().Unix()
	userToken.Expiretime = time.Now().Unix() + global.BA_CONFIG.Token.Expire
	if _, err := o.Insert(&userToken); err != nil {
		return false
	}
	return true
}

func (ts *TokenService) Delete(token string) bool {
	fmt.Println("准备删除")
	o := orm.NewOrm()
	_, err := o.Delete(&models.UserToken{Token: ts.getEncryptedToken(token)})
	if err != nil {
		fmt.Println("删除失败")
		return false
	}
	fmt.Println("删除成功")
	return true
}

func (*TokenService) getEncryptedToken(token string) string {
	hasher := ripemd160.New()
	hasher.Write([]byte(global.BA_CONFIG.Token.Key + token))
	hashBytes := hasher.Sum(nil)
	hashString := fmt.Sprintf("%x", hashBytes)
	return hashString
}
